//渲染返回键 跳转作用
if (window.location.hash.indexOf('camboadd') > -1) {
    document.querySelector(
        ".current-page"
    ).innerHTML = `
<span class="back" style="cursor:pointer;font-weight:100;">
<i class="layui-icon layui-icon-return"></i>
<span class="return">返回</span>
</span>
<span style="padding:0 10px;">|</span>
<span class="location">${window.location.hash.indexOf('cabmoadd') > -1 ? '新建套餐' : '新建套餐'}</span>
`
}

//点击返回键返回主页面
$('.return').click(function () {
    location.href = '/index.html#/cambo'
    window.location.reload();
})

// 点击预览区 上传图片
$('#btnChooseImage').on('click', function () {
    $('#coverFile').click()
})

//失去焦点
$('.pl-getf').on('blur', function () {
    // alert(2)
    // console.log((this));
    let val = $(this).val().trim()
    if (val == '') {
        $(this).addClass('getred').siblings('span').fadeIn()
        // console.log($(this));
        // $(this).siblings('span').fadeout()
    } else {
        $(this).removeClass('getred').siblings('span').fadeOut()
    }

})

const type = 2

var $image = $('#image')

// 获取分类的数据,渲染到下拉列表
initCate()
function initCate() {
    // 获取分类的数据
    $.ajax({
        method: 'get',
        url: 'http://121.4.102.44:8083/category/list' + '?type=' + type,
        success: function (res) {
            const htmlStr = template('pl-list', res)
            $('[name=categoryId]').html(htmlStr)
            // 重新渲染下拉列表(option是动态插入的)
            layui.form.render()
        }
    })
}
var msg
var caid
layui.form.on('select(categoryId)', function (data) {
    caid = data.value;
});

let caihtmlStr = null
renderPoplayer()
//点击套餐菜品
$('.pl-addSonlist').on('click', function () {
    // console.log(caihtmlStr);
    layer.open({
        title: false,
        closeBtn: false,
        type: 1,
        content: caihtmlStr,
        area: '780px'
    });
})

//封装函数获取套餐菜品分类并渲染到弹出层列表
function renderPoplayer() {
    $.ajax({
        method: 'get',
        url: 'http://121.4.102.44:8083/category/list?type=1',
        success(res) {
            // console.log(res);
            if (res.code != 1) {
                return layer.msg(res.msg, {
                    icon: 5
                })
            }
            caihtmlStr = template('pl-ymym', res)

        }
    })
}

//点击li 渲染第二个列表
$('html').on('click', '.gun', function () {
    let id = $(this).attr('data-id')
    // console.log(id);
    renderSecond(id)
})

//封装函数 渲染第二个列表
function renderSecond(id) {
    $.ajax({
        method: 'get',
        url: 'http://121.4.102.44:8083/dish/list?categoryId=' + id,
        success(res) {
            // console.log(res);
            if (res.code !== 1) {
                return layer.msg(res.msg, {
                    icon: 5
                })
            }

            const kiki = template('koko', res)
            // console.log(kiki);
            $('#qiaqia').html(kiki)
            if (res.data.length < 1) {
                $('.no').show()
                $('.else').hide()
            } else {
                $('.no').hide()
                $('.else').show()
            }

        }
    })
}

//数量判定过滤函数
template.defaults.imports.numBall = function (val) {
    if (val.length > 6) {
        val = val.substr(0, 7) + '..'
        // console.log(val);
        return val
    } else {
        return val
    }
}

//勾选选框 选定菜品
let fakeres = {
    // copies: 1,
    // dishId: "1533463247510949890",
    // name: "7878",
    // price: 123123
}
let fakedata = []
let length = null
$('html').on('change', '.sha', function () {
    // console.log(fakeres);
    if ($(this).prop('checked', true)) {
        let id = $(this).attr('data-id')
        let name = $(this).parent().siblings('.pl-listname').attr('data-name')
        let price = $(this).parent().siblings('.fan').find('.listprice').html()
        let obj = {
            name,
            price,
            id,
        }
        fakedata.push(obj)

        fakeres.data = fakedata
        fakeres.length = fakedata.length

    }
    console.log(fakeres);

    let htmlStr = template('caicai', fakeres)
    $('.sm-chose').html(htmlStr)

})


//点击取消 删除选中商品
$('html').on('click', '.pl-dellist', function () {
    let id = $(this).attr('data-id')
    fakeres.data.forEach((val, index) => {
        if (val.id == id) {
            fakeres.data.splice(index, 1)
        }
        // console.log(fakeres.data);
    })
    fakeres.length -= 1
    let htmlStr = template('caicai', fakeres)
    $('.sm-chose').html(htmlStr)

})

// 点击弹出层的取消键
$('html').on('click', '.clone-index', function (e) {

    e.preventDefault()
    layer.close(layer.index)
    fakeres.data = []
    fakeres.length = null
    fakedata = []
    let htmlStr = template('caicai', fakeres)
    $('.sm-chose').html(htmlStr)
    console.log(fakeres);
})

//点击弹出层确认 
$('html').on('click', '.sure-index', function () {
    layer.close(layer.index)
    if (fakeres.length >= 1) {
        $('#firstjo').hide()
        $('.pl-addcaibox').show()
        renderAddre()
        // console.log(fakeres);
    } else {
        $('#firstjo').show()
        $('.pl-addcaibox').hide()
    }
})

//减少键禁用功能
function disnum() {
    let num = $('.pl-jonum').html()
    if (parseInt(num) <= 1) {
        $('.rudecnum').parent().addClass('layui-btn-disabled')
    } else {

        $('.rudecnum').parent().removeClass('layui-btn-disabled')
        // console.log(1);
    }
}
// 数量增减功能
$('html').on('click', '.addnum', function () {
    let num = $(this).parent().siblings('.change').find('i').html().trim()
    let id = $(this).parent().siblings('.change').find('i').attr('data-id')
    num = parseInt(num)
    num++
    $(`.pl-jonum[data-id=${id}]`).html(num)

    disnum()
})
$('html').on('click', '.rudecnum', function () {
    let num = $(this).parent().siblings('.change').find('i').html().trim()
    if (num > 1) {
        num = parseInt(num)
        num--
        $('.pl-jonum').html(num)
    }
    disnum()
})

//封装函数 渲染增减模板
function renderAddre() {
    const htmlStr = template('moban-f', fakeres)
    $('.aoye').html(htmlStr)
}
renderAddre()

//点击确认后列表删除功能
$('html').on('click', '.gabugabu', function () {
    let id = $(this).attr('data-id')
    fakeres.data.forEach((val, index) => {
        if (val.id == id) {
            fakeres.data.splice(index, 1)
        }
        // console.log(fakeres.data);
    })
    if (fakeres.data.length >= 1) {
        $('#firstjo').hide()
        $('.pl-addcaibox').show()
        renderAddre()
        // console.log(fakeres);
    } else {
        $('#firstjo').show()
        $('.pl-addcaibox').hide()
    }
})


// 当用户选择了新文件,则更换裁剪区域的图片
$('#coverFile').on('change', function () {
    // 获取用户选择的文件列表(文件选择框dom对象,files)
    const fileList = this.files
    if (fileList.length <= 0) {
        return layui.layer.msg('请选择图片文件', {
            icon: 5
        })
    }
    $('#image').css('display', 'block')
    const file = fileList[0]
    const newImgUrl = URL.createObjectURL(file)
    $image
        .cropper('destroy')
        .attr('src', newImgUrl) // 重新设置图片的路径

    let form = new FormData()
    form.append('file', file);
    $.ajax({
        method: 'post',
        data: form,
        contentType: false,
        processData: false,
        url: 'http://121.4.102.44:8083/common/upload',
        success: function (res) {
            msg = res.data
        },
    })
})

//点击保存按键 保存数据 并跳转主页面
$("body").on("click", ".saveMsg", function (e) {
    e.preventDefault()
    $.ajax({
        method: 'post',
        url: 'http://121.4.102.44:8083/setmeal',
        contentType: 'application/json',
        data: JSON.stringify({
            name: $('#pl-getf').val().trim(),
            categoryId: caid,
            price: parseInt($('#pl-priceha').val().trim()),
            image: msg,
            status: 1,
            code: '',
            description: $('#pl-kj').val().trim(),
            dishList: [],
            setmealDishes: [{
                copies: 1,
                dishId: "1533444676764422145",
                name: "驱蚊器我",
                price: 111
            }]

        }),
        success(res) {
            console.log(res);
            // $('.return').click()
        }
    })

})

//点击取消
$('#backList').on('click', function () {
    location.href = '/index.html#/cambo'
    window.location.reload();
})

//点击保存并继续编辑
$('.saveadd').click(function (e) {
    e.preventDefault()
    $.ajax({
        method: 'post',
        url: 'http://121.4.102.44:8083/setmeal',
        contentType: 'application/json',
        data: JSON.stringify({
            name: $('#pl-getf').val().trim(),
            categoryId: caid,
            price: parseInt($('#pl-priceha').val().trim()),
            image: msg,
            status: 1,
            code: '',
            description: $('#pl-kj').val().trim(),
            dishList: [],
            setmealDishes: [{
                copies: 1,
                dishId: "1533444676764422145",
                name: "驱蚊器我",
                price: 111
            }]

        }),
        success(res) {

            layui.layer.msg('添加成功', {
                icon: 6
            })
        }
    })
})
